import axios from 'axios'
const instance = axios.create({
  timeout: 3600000,
})

// http request 拦截器
instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${sessionStorage.token || ''}`
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
// http response 拦截器
instance.interceptors.response.use(
  (response) => {
    return Promise.resolve(response)
  },
  (error) => {
    return Promise.reject(error)
  }
)
// get 方法封装
export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance.get(url, { params: params }).then((response) => {
      resolve(response.data)
    }).catch((err) => {
      reject(err)
    })
  })
}

// post 方法封装
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    instance.post(url, data).then(response => {
      resolve(response.data)
    }, err => {
      reject(err)
    })
  })
}

// 下载封装
export function exportFile(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance.get(url, { params: params, responseType: 'blob' }).then((response) => {
      resolve(response)
    }).catch((err) => {
      reject(err)
    })
  })
}

// post 附件上传
export function upload(url, data = {}, contentType = 'application/json') {
  return new Promise((resolve, reject) => {
    instance({ url, method: 'post', data, headers: { 'Content-Type': contentType }}).then(response => {
      resolve(response.data)
    },
    err => {
      reject(err)
    })
  })
}
